﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace UFrame
{
    /// <summary>
    /// 下载类
    /// streamingAssetsPath 不支持File Directory类的公共方法
    /// </summary>
    public class DownMaMono : MaMono<DownMaMono>
    {
        public static string serverUrl = "http://192.168.31.228:80/unity/server.txt";
        public static string serverUnityUrl = "htfotp://192.168.31.228:80/unity/";
        public static ServerVersion localVersion;
        public static string versionFile = "server.txt";
        public static string mapAssetFile = "mapAsset.txt";
        public static Dictionary<string, string> localAssetMap = new Dictionary<string, string>();
        public static Dictionary<string, string> serverAssetMap = new Dictionary<string, string>();
        public static Dictionary<string, string> downFileList = new Dictionary<string, string>(); //需要下载的文件列表

        public static event Action OnCheckLocalVersion;
        public static event Action<string, AssetBundle> OnFileComplete;


        protected void Awake()
        {
            base.Awake();
            TextAsset t = Resources.Load<TextAsset>("version");
            localVersion = RefLineToObjectTool.AnalyzeTxt<ServerVersion>(t.text);
        }

        public static IEnumerator Down()
        {
            UnityWebRequest request = UnityWebRequest.Get(serverUrl);
            yield return request.SendWebRequest();
            string s = request.downloadHandler.text;
            ServerVersion serverVersion = RefLineToObjectTool.AnalyzeTxt<ServerVersion>(s);

            //资源map文件
            string serverAssetPath = serverUnityUrl + "/" + serverVersion.Version.ToString();
            string serverMapAssetPath = serverAssetPath + "/" + mapAssetFile;
            request = UnityWebRequest.Get(serverMapAssetPath);
            yield return request.SendWebRequest();
            string mapTxt = request.downloadHandler.text;
            AnalyzeMapTxt(mapTxt, serverAssetMap);


            //对比,然后是加入下载
            CheckAssetVersion();
            foreach (var item in downFileList)
            {
                string filePath = serverAssetPath + "/" + item.Key;
                request = UnityWebRequest.Get(filePath);
                yield return request.SendWebRequest();
                if (request.isNetworkError || request.error != null)
                {
                    Debug.LogError("文件下载出错:" + filePath + request.error);
                }
                else
                {
                    //保存assetbundle
                    SaveFile(request.downloadHandler.data, item.Key);
                    localAssetMap[item.Key] = item.Value;
                    SaveMapFile(localAssetMap);
                    if (OnFileComplete != null)
                    {
                        OnFileComplete(item.Key, DownloadHandlerAssetBundle.GetContent(request));
                    }
                }

                yield return new WaitForEndOfFrame();
            }

            Debug.Log("下载完毕 " + Application.persistentDataPath + "/" + mapAssetFile);
        }


        public static IEnumerator CheckVersion()
        {
            UnityWebRequest request = null;
            string text = string.Empty;
            string downVersionFile = Application.persistentDataPath + "/" + versionFile;
            if (File.Exists(downVersionFile))
            {
                text = File.ReadAllText(downVersionFile,Encoding.UTF8);
                Debug.Log("读取本地: " + text);
            }
            else
            {
                string pcPath = Application.streamingAssetsPath + "/" + versionFile;
                request = UnityWebRequest.Get(pcPath);
                yield return request.SendWebRequest();
            }

            //读取map文件
            string downMapFile = Application.persistentDataPath + "/" + mapAssetFile;
            if (File.Exists(downMapFile))
            {
                text = File.ReadAllText(downMapFile,Encoding.UTF8);
                Debug.Log("读取本地Map: " + text);
            }
            else
            {
                string mapAssetPath = Application.streamingAssetsPath + "/" + mapAssetFile;
                request = UnityWebRequest.Get(mapAssetPath);
                yield return request.SendWebRequest();
                text = request.downloadHandler.text;
            }

            //map加入字段比对
            AnalyzeMapTxt(text, localAssetMap);
            yield return 0;

            if (OnCheckLocalVersion != null)
            {
                OnCheckLocalVersion();
            }
        }

        public static void SaveFile(byte[] data, string fileName)
        {
            FileStream fs = File.Create(Application.persistentDataPath + "/" + fileName);
            fs.Write(data, 0, data.Length);
            fs.Close();
        }

        public static void SaveMapFile(Dictionary<string, string> map)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in map)
            {
                sb.AppendLine(string.Format("{0}:{1}", item.Key, item.Value));
            }

            string versionInfo = sb.ToString();


            using (FileStream fs = File.Create(Application.persistentDataPath + "/" + mapAssetFile))
            {
                StreamWriter sw = new StreamWriter(fs, Encoding.ASCII);
                try
                {
                    sw.Write(versionInfo);

                    sw.Close();
                    fs.Close();
                    fs.Dispose();
                }
                catch (IOException e)
                {
                    Debug.LogError(e.Message);
                }
            }
        }

        private static void AnalyzeMapTxt(string text, Dictionary<string, string> map)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            string[] mapLines = text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            foreach (var line in mapLines)
            {
                string[] keyValue = line.Split(':');
                if (string.IsNullOrEmpty(keyValue[0]) == false)
                {
                    map.Add(keyValue[0], keyValue[1]);
                }
            }
        }

        /// <summary>
        /// 检查asset的MD5码 查看是否一样
        /// </summary>
        private static void CheckAssetVersion()
        {
            bool has = false;
            foreach (var server in serverAssetMap)
            {
                has = false;
                foreach (var local in localAssetMap)
                {
                    if (local.Key == server.Key && local.Value != server.Value)
                    {
                        //需要下载服务器
                        has = true;
                        downFileList.Add(server.Key, server.Value);
                        break;
                    }
                    else if (local.Key == server.Key && local.Value == server.Value)
                    {
                        has = true;
                    }
                }

                if (has == false)
                {
                    //客户端不存在的资源包
                    downFileList.Add(server.Key, server.Value);
                }
            }
        }

        public class ServerVersion
        {
            public float Version;
            public string AssetPath;
        }
    }
}